package com.echovin.esb.gateway.locator;

import com.echovin.esb.gateway.model.GatewayParameterSchema;
import com.echovin.esb.gateway.service.GatewayParameterValidateService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
public class GatewayParameterValidateResourceLocator {
    private Map<String, GatewayParameterSchema> resourceMap = new ConcurrentHashMap<>();
    @Autowired
    GatewayParameterValidateService gatewayParameterValidateService;
    @Autowired
    GatewayServiceResourceLocator gatewayServiceResourceLocator;
    @Autowired
    GatewayServiceActionResourceLocator gatewayServiceActionResourceLocator;

    public GatewayParameterValidateResourceLocator() {
    }

    /**
     * 清空缓存并刷新
     */
    public void refresh() {
        this.resourceMap.clear();
        this.resourceMap.putAll(this.loadResourceDefine());
    }

    /**
     * path->schema
     * @param requestPath
     * @return
     */
    public String getSchema(String requestPath) {
        if (StringUtils.isEmpty(requestPath)) {
            return null;
        }
        String serviceId = gatewayServiceResourceLocator.getServiceId(requestPath);
        if (StringUtils.isEmpty(serviceId)) {
            return null;
        }
        String actionId = gatewayServiceActionResourceLocator.getServiceActionId(serviceId);
        if (StringUtils.isEmpty(actionId)) {
            return null;
        }
        GatewayParameterSchema gatewayServerAction = this.resourceMap.get(actionId);
        if (gatewayServerAction == null) {
            return null;
        }
        return gatewayServerAction.getSchema();
    }

    /**
     * 调用service查询所有的gateway服务动作，组装{[actionId：gatewayParameterSchema]}
     */
    private Map<String, GatewayParameterSchema> loadResourceDefine() {
        Map<String, GatewayParameterSchema> map = new ConcurrentHashMap<>();
        try {
            List<GatewayParameterSchema> resourceList = gatewayParameterValidateService.getParameterValidates();
            if (resourceList == null) {
                return map;
            }

            Iterator var3 = resourceList.iterator();
            while(var3.hasNext()) {
                GatewayParameterSchema resource = (GatewayParameterSchema)var3.next();
                map.put(resource.getActionId(), resource);
            }

        } catch (Exception e) {
            log.error("加载gateway参数校验schema错误:{}", e);
        }

        log.info("数据库加载参数校验schema{}", map.values());

        return map;
    }

}
